﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Reflection;
using System.Diagnostics;
using RichTextEditor;

namespace RichTextEditor
{
    [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
    [Guid("7B6BED7E-6C42-438F-9632-4C6E65686697")]
    public interface IRichTextEditor 
    {
        string RichText { get; set; }
        byte[] ImageData { get; set; }

        event OnRichTextHandler OnRichText;
        event OnImageHandler OnImage;
        event OnCloseHandler OnClose;

        void LoadEditor();
    } 

    [ProgId("RichTextEditor.Editor")]
    [ClassInterface(ClassInterfaceType.None), ComSourceInterfaces(typeof(Events))]
    [Guid("3F709351-AA54-4929-AEC7-88BB265F3B41")]
    [ComVisible(true)]
    public class ComLoader : IRichTextEditor
    {
        public string RichText { get; set; }
        public byte[] ImageData { get; set; }

        public event OnRichTextHandler OnRichText;
        public event OnImageHandler OnImage;
        public event OnCloseHandler OnClose;

        public void LoadEditor()
        {
            var editor = new EditorWindow();

            editor.RichText = this.RichText;
            editor.ImageData = this.ImageData;

            editor.OnRichText += (t) =>
            {
                if (OnRichText != null)
                {
                    OnRichText(t);
                }
            };

            editor.OnImage += (i) =>
            {
                if (OnImage != null)
                {
                    OnImage(i);
                }
            };

            var result = editor.ShowDialog();

            if (OnClose != null)
            {
                OnClose();
            }
        }
    }

    public delegate void OnRichTextHandler(string richText);
    public delegate void OnImageHandler(byte[] imageData);
    public delegate void OnCloseHandler();

    /// <summary>
    /// This interface shows events to javascript
    /// </summary>
    [Guid("76279926-CCCE-4922-869E-9D369271877B")]
    [InterfaceType(ComInterfaceType.InterfaceIsIDispatch)]
    public interface Events
    {
        [DispId(0x60020001)]
        void OnRichText(string richText);
        [DispId(0x60020002)]
        void OnImage(byte[] imageData);
        [DispId(0x60020003)]
        void OnClose();
    }
}
